package com.itheima.reggie.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Category;
import com.itheima.reggie.domain.Dish;
import com.itheima.reggie.domain.DishFlavor;
import com.itheima.reggie.domain.SetmealDish;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.mapper.DishFlavorMapper;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.mapper.SetmealDishMapper;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;

/**
 * @author zsk
 * @create 2022-02-15-16:32
 */
@Service
@Slf4j
public class DishServiceImpl implements DishService {

    //依赖注入
    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;

    //查询所有，分页显示
    @Override
    public Page<Dish> findByPage(Integer pageNum, Integer pageSize, String name) {

        //设置查询条件
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        //先根据姓名模糊查询（先判断非空，然后where name = "%#{name}%" 为条件查询）
        wrapper.like(StringUtils.isNoneEmpty(name), Dish::getName, name);

        //使用分页插件查询菜品表(参数传递设置好的页数及条数)
        Page<Dish> page = new Page<>(pageNum, pageSize);
        page = dishMapper.selectPage(page, wrapper);
        System.out.println(page);

        //根据菜品的分类查询分类信息
        List<Dish> dishList = page.getRecords();//getRecords:当前页数据
        if (CollectionUtil.isNotEmpty(dishList)) {//非空判断
            for (Dish dish : dishList) {
                //查询出当前菜品的分类(根据dish表中的字段categoryId为查询条件)
                Category category = categoryMapper.selectById(dish.getCategoryId());
                //菜品分类名称:CategoryName（把查询到的分类存储到dish表中的字段中）
                dish.setCategoryName(category.getName());

                //根据菜品的id从口味表中查询当前菜品的口味列表
                LambdaQueryWrapper<DishFlavor> wrapper1 = new LambdaQueryWrapper<>();
                //设置查询条件（where dish_id = #{id}）
                wrapper1.eq(DishFlavor::getDishId, dish.getId());
                //查询
                List<DishFlavor> dishFlavors = dishFlavorMapper.selectList(wrapper1);

                //放入到dish中
                dish.setFlavors(dishFlavors);
            }
        }
        //返回分页结果
        return page;
    }

    @Transactional//需要控制事务
    @Override
    public void save(Dish dish) {

        //添加菜品基本信息
        log.info("保存菜品之前的dish对象：" + dish);
        dishMapper.insert(dish);
        log.info("保存菜品之后的dish对象：" + dish);

        //获取菜品口味
        List<DishFlavor> dishFlavorList = dish.getFlavors();
        //进行非空判断
        if (CollectionUtil.isNotEmpty(dishFlavorList)) {
            for (DishFlavor dishFlavor : dishFlavorList) {
                //根据id存储到对应的菜品中
                dishFlavor.setDishId(dish.getId());
                //保存每个菜品的id，调用mapper执行添加语句
                dishFlavorMapper.insert(dishFlavor);
            }
        }


    }

    //根据id查询数据
    @Override
    public Dish findById(Long id) {

        //先根据id查询菜品信息
        Dish dish = dishMapper.selectById(id);

        //再根据查询到的菜品信息查询对应的口味信息
        LambdaQueryWrapper<DishFlavor> wrapper1 = new LambdaQueryWrapper<>();
        //确定查询条件
        wrapper1.eq(DishFlavor::getDishId, dish.getId());
        //调用dishFlavorMapper查询
        List<DishFlavor> dishFlavorList = dishFlavorMapper.selectList(wrapper1);
        //存储到dish表中的flavors（菜品口味列表）字段里
        dish.setFlavors(dishFlavorList);

        //返回结果
        return dish;

    }

    //修改菜品信息
    //加入事物
    @Transactional
    @Override
    public void update(Dish dish) {
        //调用mapper层修改菜品信息,根据传递过来的id修改
        dishMapper.updateById(dish);

        //修改口味信息,先删除原有的口味信息，然后重新添加
        LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
        //相当与where id = #{id}
        wrapper.eq(DishFlavor::getDishId, dish.getId());
        //调用dishFlavorMapper层删除
        dishFlavorMapper.delete(wrapper);

        //重新保存口味信息
        List<DishFlavor> dishFlavorList = dish.getFlavors();
        //非空判断
        if (CollectionUtil.isNotEmpty(dishFlavorList)) {
            //遍历存储
            for (DishFlavor dishFlavor : dishFlavorList) {
                //根据对应的id存储到相应的菜品中
                dishFlavor.setDishId(dish.getId());

                //调用dishFlavorMapper存储对应的口味信息
                dishFlavorMapper.insert(dishFlavor);
            }
        }

    }

    //删除菜品
    //添加事物管理
    @Transactional
    @Override
    public void deleteById(Long[] ids) {
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(Dish::getId, ids);
        wrapper.eq(Dish::getStatus, 1);
        int count = dishMapper.selectCount(wrapper);
        if (count > 0) {
            throw new CustomException("要删除的菜品还在在售状态,不能删除");
        }

        // 遍历删除
        for (Long id : ids) {
            //根据菜品id删除菜品的口味列表
            LambdaQueryWrapper<DishFlavor> wrapper2 = new LambdaQueryWrapper<>();
            wrapper2.eq(DishFlavor::getDishId, id);
            dishFlavorMapper.delete(wrapper2);

            //根据菜品id删除菜品信息
            dishMapper.deleteById(id);
        }
    }


    //批量启售/禁售
    @Transactional
    @Override
    public void updateStatus(Integer status, long[] ids) {
        for (Long id : ids) {
            //update dish set status = #{} where id = #{}
            Dish dish = new Dish();
            dish.setId(id);
            dish.setStatus(status);
            dishMapper.updateById(dish);
        }
    }

    //根据菜品分类id查询菜品
    @Override
    public List<Dish> findByCategoryId(Long categoryId,String name) {

        //封装查询条件
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        //相当于where dish_category = #{id} and status = 1
        wrapper.eq(Dish::getCategoryId,categoryId).eq(Dish::getStatus,1).or().like(Dish::getName,name);
        //调用mapper层查询
        List<Dish> dishList = dishMapper.selectList(wrapper);
        //查询菜品下的口味信息
        //非空判断
        if (CollectionUtil.isNotEmpty(dishList)){
            for (Dish dish : dishList) {
                //从口味表中查询口味信息
                LambdaQueryWrapper<DishFlavor> wrapper1 = new LambdaQueryWrapper<>();
                //构建查询条件
                wrapper1.eq(DishFlavor::getDishId,dish.getId());
                List<DishFlavor> dishFlavorList = dishFlavorMapper.selectList(wrapper1);
                //放入dish表中数据
                dish.setFlavors(dishFlavorList);
            }
        }
        //返回数据
        return dishList;
    }


}
